<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
            <el-form-item prop="searchValue">
                <el-input v-model="queryParams.searchValue" placeholder="请输入订单编号、业务单元、项目名称、图号等" clearable
                    style="width: 340px" @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="订单状态" clearable style="width: 240px">
                    <el-option v-for="dict in options" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
            </el-form-item>

            <el-form-item label="导入时间">
                <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete">批量删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport">订单导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">订单新增</el-button>
            </el-col>
        </el-row>

        <el-table v-loading="loading" :data="processList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column label="订单编号" key="orderCode" prop="orderCode" :show-overflow-tooltip="true" width="130" />
            <el-table-column label="业务单元" prop="businessUnit" :show-overflow-tooltip="true" width="150" />
            <el-table-column label="项目名称" prop="proTitle" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="图号" prop="graphid" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="机组编号" prop="unitCode" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="用料部门" prop="deptName" :show-overflow-tooltip="true" width="120" />
            <el-table-column label="计划数量" prop="planNum" width="80" />
            <el-table-column label="订单时间" align="center" prop="createTime" width="100">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)">详情</el-button>
                    <el-button size="mini" type="text" icon="el-icon-s-promotion"
                        @click="handleIssue(scope.row)">下发</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 订单导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.import" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?formValue=' + upload.value" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.import = false">取 消</el-button>
            </div>
        </el-dialog>


        <!-- 订单导入对话框 -->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>

            <el-select v-model="upload.value" placeholder="请选择模板" clearable style="width: 240px">
                <el-option v-for="type in formTypes" :key="type.value" :label="type.label" :value="type.value" />
            </el-select>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>


        <!-- 新增订单对话框 -->
        <el-dialog :title="title" :visible.sync="add" width="600px" append-to-body>
            <el-form :rules="rules" ref="form" :model="form" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单编号" prop="orderCode">
                            <el-input v-model="form.orderCode" placeholder="请生成订单编号" maxlength="20" clearable
                                :disabled="true" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-button type="primary" style="margin-left: 10px; font-size: 10px;" size="mini"
                            @click="autoCreateCode">编号自动生成</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务单元" prop="businessUnit">
                            <el-select v-model="form.businessUnit" placeholder="请选择业务单元" clearable>
                                <el-option v-for="item in businessOptions" :key="item.value" :label="item.label"
                                    :value="item.label">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="项目名称" prop="proTitle">
                            <el-input v-model="form.proTitle" placeholder="请输入项目名称" maxlength="30" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="图号" prop="graphid">
                            <el-input v-model="form.graphid" placeholder="请输入图号" maxlength="30" clearable
                                onkeyup="value = value.replace(/[\W]/g, '')" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机组编号" prop="unitCode">
                            <el-input v-model="form.unitCode" placeholder="请输入机组编号" maxlength="30" clearable
                                onkeyup="value = value.replace(/[\W]/g, '')" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用料部门" prop="deptName">
                            <el-input v-model="form.deptName" placeholder="请输入用料部门" maxlength="30" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入备注" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="计划数量" prop="planNum">
                            <el-input v-model="form.planNum" placeholder="请输入计划数量" clearable
                                onkeyup="value=value.replace(/[^\d]/g,'')" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单位" prop="unit">
                            <el-input v-model="form.unit" placeholder="请输入单位" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAdd">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

    </div>
</template>
  
<script>
import { getToken } from "@/utils/auth";
import { queryProOrder, delProOrder, getProOrderInfo, addProOrder, updateProOrder, getGenerateNumber } from "@/api/process/order";

export default {
    name: "List",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            //是否显示弹出层（新增订单）
            add: false,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            // 加工订单数据
            processList: [],
            // 日期范围
            dateRange: [],
            // 表单参数,该订单数据
            form: {
                orderCode: undefined,
                businessUnit: undefined,
                proTitle: undefined,
                proTitle: undefined,
                graphid: undefined,
                unitCode: undefined,
                deptName: undefined,
                remark: undefined,
                planNum: undefined,
                unit: undefined
            },
            //标题
            title: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                searchValue: undefined,
                status: undefined
            },
            rules: {
                businessUnit: [
                    { required: true, message: '请选择业务单元', trigger: 'change' }
                ],
                proTitle: [
                    { required: true, message: '请输入项目名称', trigger: 'blur' }
                ],
                graphid: [
                    { required: true, message: '请输入图号', trigger: 'blur' }
                ],
                unitCode: [
                    { required: true, message: '请输入机组编号', trigger: 'blur' }
                ],
                deptName: [
                    { required: true, message: '请输入用料部门', trigger: 'blur' }
                ],
            },
            //业务单元
            businessOptions: [{
                value: '0',
                label: '溴冷机'
            }, {
                value: '1',
                label: '新能源'
            }, {
                value: '2',
                label: '空冷器'
            }, {
                value: '3',
                label: '换热器'
            }, {
                value: '4',
                label: '锅炉'
            }, {
                value: '5',
                label: '物流事业部'
            }],
            //状态
            options: [{
                value: '0',
                label: '未下发'
            }, {
                value: '1',
                label: '已下发'
            }, {
                value: '2',
                label: '已完成'
            }],

            //模板类型
            formTypes: [{
                value: '0',
                label: '换热器-杂件模板'
            }, {
                value: '1',
                label: '换热器-正常件模板'
            }, {
                value: '2',
                label: '新能源-杂件模板'
            }, {
                value: '3',
                label: '新能源-正常件模板'
            }, {
                value: '4',
                label: '锅炉-杂件模板'
            }, {
                value: '5',
                label: '锅炉-正常件模板'
            }],

            // 用户导入参数
            upload: {
                // 是否显示弹出层（订单模版选择）
                open: false,
                // 是否显示弹出层（订单上传）
                import: false,
                // 弹出层标题（订单导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 当前模板
                value: '',
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/process/order/importData"
            },
        };
    },

    created() {
        this.getList();
    },

    methods: {
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.resetForm("queryForm");
            this.queryParams.searchValue = undefined;
            this.queryParams.status = undefined;
            this.handleQuery();
        },

        /** 跳转详情页面 */
        handleDetail: function (row) {
            this.$router.push({ path: "/process/detail/", query: { orderCode: row.orderCode } })
        },

        /** 下发 */
        handleIssue(row) {
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            const orderCodes = row.orderCode || this.ids;
            this.$modal.confirm('是否确认删除订单编号为"' + orderCodes + '"的数据项？').then(function () {
                return delProOrder(orderCodes);
            }).then(() => {
                this.handleQuery();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.orderCode);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },

        /**获取列表数据*/
        getList() {
            this.loading = true;
            queryProOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                this.processList = response.rows;
                this.total = response.total;
                this.loading = false;
            }
            );

        },
        /** 导入按钮操作 */
        handleImport() {
            this.upload.title = "选择模板";
            this.upload.open = true;
        },
        //订单新增
        handleAdd() {
            this.title = "新增订单"
            this.add = true;
            this.reset();
        },
        //订单编辑
        handleEdit(row) {
            this.reset();
            this.title = "编辑订单"
            this.loading = true;
            getProOrderInfo(row.orderCode).then(response => {
                this.loading = false;
                this.form = response.data
                this.add = true;
            }
            );

        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.import = false;
            this.upload.value = '';
            this.$refs.upload.clearFiles();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
            this.upload.isUploading = false;
            this.getList();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        /** 导入按钮操作 */
        submitForm() {
            if (typeof this.upload.value === 'undefined' || this.upload.value == null || this.upload.value === '') {
                this.$message({
                    message: '请先选择导入订单模板！',
                    type: 'warning'
                });
            } else {
                this.upload.title = "订单导入";
                this.upload.open = false;
                this.upload.import = true;
            }

        },
        // 取消按钮
        cancel() {
            this.add = false;
            this.$refs.form.clearValidate();
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                orderCode: undefined,
                businessUnit: undefined,
                proTitle: undefined,
                proTitle: undefined,
                graphid: undefined,
                unitCode: undefined,
                deptName: undefined,
                remark: undefined,
                planNum: undefined,
                unit: undefined
            }
        },
        //提交新增订单或编辑订单
        submitAdd() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.proId != undefined) {
                        updateProOrder(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.add = false;
                        });
                    } else {
                        addProOrder(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.add = false;
                        });
                    }
                    this.handleQuery();
                    this.$refs.form.clearValidate();

                }
            })


        },
        //自动生成编号
        autoCreateCode() {
            if (Object.keys(this.form).length != 0 && this.form.proId != null) {
                this.$message({
                    message: '已有编号，如果需要生成新编号，请先删除该订单',
                    type: 'warning'
                });
            } else if (this.form.businessUnit == undefined) {
                this.$message({
                    message: '请先选择业务单元',
                    type: 'warning'
                });
            } else {
                getGenerateNumber(this.form.businessUnit).then(response => {
                    this.form.orderCode = response.data
                });
            }
        }
    }

};
</script>